package com.education.project.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.education.project.model.WebUser;

@Component
public class WebInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		String contextPath = session.getServletContext().getContextPath();
		WebUser webUser = (WebUser) session.getAttribute("webUser");
		if(webUser!=null) {
			return true;
		}
		if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
			response.setStatus(402);
		} else {
			response.sendRedirect(contextPath+"/login");
		}
		return false;
	}
}
